<script setup lang="ts">
import modalBody from './modal-body.vue';
import { doPlaningOperation, doGetPlanOperationProgress } from '@/api/demand/arithmetic/index';
import { Message, Modal } from '@/instance';
import type { PlaningOperationParams } from '@/api/demand/arithmetic/model/type';

const props = defineProps<{
    ids: (string | number)[];
}>();

const visible = ref(false);

type OperationType = keyof typeof tipMessage;
type Params = Omit<PlaningOperationParams, 'orderNumber' | 'planningOperationType'>;

let planningOperationType: OperationType;
let params: Params;

const open = (type: string, operationParams?: Params) => {
    visible.value = true;
    planningOperationType = type as OperationType;
    params = operationParams ?? {};
    planingOperation();
};

/**
 * @: 拿到id开始计划运算
 * @param {*} const
 * @return {*}
 */
const planingOperation = async () => {
    try {
        const { ids } = props;
        const body = {
            orderNumber: ids,
            planningOperationType,
            ...params
        };
        const { data } = await doPlaningOperation(body);
        if (data) {
            getPlanOperationProgress(data);
            return;
        }
    } catch (error) {
        console.log('error', error);
    }
    visible.value = false;
    rate.value = 0;
};

const rate = ref(0);

const emit = defineEmits(['getData', 'updateSelect']);

const tipMessage = {
    PARTIAL_OPERATION: '部分运算',
    ALL_OPERATION: '全部运算',
    ORDER_INSERT_OPERATION: '插单排产',
    CANCEL_OPERATION: '取消排产',
    AGAIN_OPERATION: '重新排产',
    TERMINATE_OPERATION: '终止排产'
} as const;

const customMessage = ['取消排产', '终止排产'];

const getMessage = () => {
    const type = tipMessage[planningOperationType];

    if (customMessage.includes(type)) {
        const { ids } = props;
        const success = params?.synDeleteOrder
            ? `${type}成功！已${type}并删除${ids}条订单！已更新排程计划！`
            : `${type}成功！已${type}${ids}条订单！已更新排程计划！`;

        return { success, error: `${type}失败！` };
    }

    return { success: `${type}成功！已更新排程计划！`, error: `${type}失败！` };
};

/**
 * @: 进行计划运算
 */
let timer: number;
const getPlanOperationProgress = (id: string) => {
    clearInterval(timer);
    timer = window.setInterval(async () => {
        try {
            const { data } = await doGetPlanOperationProgress({ id });
            if (data) {
                const { status, orderIds } = data;
                if (status === 1) {
                    rate.value = data.rate;
                    if (data.rate === 100) {
                        Message.success(getMessage().success);
                        emit('getData');
                        refresh();
                    }
                } else if (status === 2) {
                    Modal.error({
                        title: getMessage().error,
                        content: h(modalBody, { text: data.failureReason }),

                        okText: '确定'
                    });
                    if (orderIds?.length) {
                        emit('updateSelect', orderIds);
                    }
                    refresh();
                }
            }
        } catch (error) {
            refresh();
        }
    }, 1500);
};

/**
 * @: 刷新会最出事的状态
 */
const refresh = () => {
    clearInterval(timer);
    visible.value = false;
    rate.value = 0;
};

defineExpose({
    open
});
</script>

<template>
    <q-modal v-model:visible="visible" :footer="false" title="" centered :closable="true">
        <div class="text">正在运算{{ rate }}%</div>

        <div class="progress">
            <div class="progress__rate" :style="{ width: rate + '%' }">
                <div class="progress__rate--run">
                    <q-icon icon-class="haomapaishibie" size="16" color="#fff" />
                </div>
            </div>
        </div>
    </q-modal>
</template>
<style scoped lang="scss">
@include b(text) {
    text-align: center;
}

@include b(progress) {
    position: relative;
    width: 402px;
    height: 8px;
    margin: 20px auto 0;
    background: rgb(0 85 221 / 30%);
    border-radius: 8px;

    @include e(rate) {
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        background: linear-gradient(270deg, var(--q-color-primary) 0%, rgb(0 102 255 / 25%) 100%);
        border-radius: 8px;

        @include m(run) {
            position: absolute;
            top: -8px;
            right: -3px;
            width: 24px;
            height: 24px;
            line-height: 23px;
            text-align: center;
            background: var(--q-color-primary);
            border-radius: 16px;
        }
    }
}

@include b(error-main) {
    position: relative;
    box-sizing: border-box;
    height: 100%;
    padding-bottom: 32px;
    @include e(title) {
        display: flex;
        align-items: center;
        font-size: 16px;
        font-weight: 700;
        color: var(--q-color-danger);
    }

    @include e(footer) {
        position: absolute;
        right: 0;
        bottom: -10px;
        z-index: 1;
    }
}

@include b(content) {
    height: 132px;
    padding-right: 20px;
    margin-right: -13px;
    margin-left: 40px;
    font-size: 14px;
    line-height: 22px;
    color: var(--q-text-color-secondary);
    text-align: justify;
}
</style>
